package org.tang.schoolproject.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.tang.schoolproject.comment.Valida;
import org.tang.schoolproject.entitys.LoginUser;
import org.tang.schoolproject.entitys.User;
import org.tang.schoolproject.service.UserService;

import java.util.Map;

@RestController
@RequestMapping("/user/")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    /**
     * 登录接口
     * @parma user
     * @return
     */
    @PostMapping("login")
    public SaResult login(@RequestBody LoginUser user) {
        return userService.login(user);
    }

    /**
     * 登出接口
     * @return
     */
    @GetMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("登出成功");
    }

    /**
     * 保存用户信息
     * @param user
     * @return
     */
    @PostMapping("save")
    public SaResult save(@Validated(Valida.Create.class) @RequestBody User user) {
        return userService.saveUser(user);
    }

    /**
     * 查询用户信息
     * @return
     */
    @GetMapping("select")
    public SaResult select() {
        return SaResult.data(StpUtil.getLoginId());
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    public SaResult update(@Validated(Valida.Update.class) @RequestBody User user) {
        return userService.updateUser(user);
    }

    /**
     * 删除用户信息
     * @param id
     * @return
     */
    @GetMapping("delete")
    public SaResult delete(Long id) {
        return userService.deleteUser(id);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping("pageUser")
    public SaResult pageUser(@RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer size,
                             @RequestParam Map<String, Object> searchMap) {
        return userService.pageUser(page, size, searchMap);
    }
}
